package com.atguigu.lease.web.admin.custom.config;

import com.atguigu.lease.web.admin.custom.converter.StringToBaseEnumConverterFactory;
import com.atguigu.lease.web.admin.custom.converter.StringToItemTypeConverter;
import com.atguigu.lease.web.admin.custom.interceptor.AuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
    // 自动注入String到ItemType的转换器
    @Autowired
    private StringToItemTypeConverter stringToItemTypeConverter;

    // 自动注入String到BaseEnum的转换工厂
    @Autowired
    private StringToBaseEnumConverterFactory stringToBaseEnumConverterFactory;

    /**
     * 向FormatterRegistry注册转换器和转换工厂
     * 此方法重写了父类中的方法，用于配置Spring MVC的转换器和格式化器
     * @param registry FormatterRegistry实例，用于注册转换器和转换工厂
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(stringToItemTypeConverter);
        registry.addConverterFactory(stringToBaseEnumConverterFactory);
    }

    // 自动注入认证拦截器
    @Autowired
    private AuthenticationInterceptor authenticationInterceptor;

    // 从配置文件中获取包含路径模式
    @Value("${admin.auth.path-patterns.include}")
    private String[] includePathPatterns;

    // 从配置文件中获取排除路径模式
    @Value("${admin.auth.path-patterns.exclude}")
    private String[] excludePathPatterns;

    /**
     * 添加拦截器到InterceptorRegistry
     * 此方法重写了父类中的方法，用于配置Spring MVC的拦截器
     * @param registry InterceptorRegistry实例，用于注册拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.authenticationInterceptor)
                .addPathPatterns(includePathPatterns)
                .excludePathPatterns(excludePathPatterns);
    }
}
